package org.xworker.rap;

import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Shell;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import org.xmeta.World;
import org.xmeta.annotation.ActionField;
import org.xmeta.util.UtilData;

import java.util.Map;

public class Login {
    @ActionField
    public ActionContext actionContext;
    @ActionField
    public Button loginButton;
    @ActionField
    public Shell shell;
    @ActionField
    public Thing thingForm;

    String name;
    String password;

    boolean isLoginEnabled() {
        Map<String, Object> values = thingForm.doAction("getValues", actionContext);
        name = UtilData.getString(values.get("name"), null);
        password = UtilData.getString(values.get("password"), null);

        if (name != null && !name.isEmpty() && password != null && !password.isEmpty()) {
            loginButton.setEnabled(true);
            return true;
        } else {
            loginButton.setEnabled(false);
            return false;
        }
    }

    public void formModified() {
        isLoginEnabled();
    }

    public void formDefaultSelection() {
        login();
    }

    public void login() {
        if (isLoginEnabled()) {
            ActionContext ac = new ActionContext();
            ac.put("parent", shell.getDisplay());

            Thing prototype = World.getInstance().getThing("org.xworker.rap.Main");
            Shell mainShell = prototype.doAction("create", ac);

            shell.dispose();

            mainShell.setVisible(true);
            mainShell.setFocus();
        }
    }

    public void exit() {
        shell.dispose();
    }
}
